<template>
  <div class="config-editor-layout">
    <!-- 头部工具栏 -->
    <div class="config-editor-header">
      <div class="header-left">
        <h1>Bot Server 配置编辑器</h1>
        <span class="config-status" :class="serverStatus">
          <el-icon><Connection /></el-icon>
          {{ serverStatusText }}
        </span>
      </div>
      <div class="header-right">
        <el-space>
          <el-button @click="toggleTheme" circle>
            <el-icon><component :is="isDark ? 'Sunny' : 'Moon'" /></el-icon>
          </el-button>
          <el-button type="primary" @click="showImportDialog = true">
            <el-icon><Upload /></el-icon>
            导入配置
          </el-button>
          <el-button @click="showExportDialog = true">
            <el-icon><Download /></el-icon>
            导出配置
          </el-button>
          <el-button @click="reloadConfigs" :loading="loading">
            <el-icon><Refresh /></el-icon>
            重新加载
          </el-button>
        </el-space>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="config-editor-main">
      <!-- 侧边栏：快速导航 -->
      <div class="config-editor-sidebar">
        <el-menu
          :default-active="$route.path"
          router
          :collapse="false"
          class="config-nav-menu"
        >
          <el-menu-item index="/configs">
            <el-icon><Grid /></el-icon>
            <span>配置概览</span>
          </el-menu-item>
          <el-menu-item index="/equipment">
            <el-icon><Box /></el-icon>
            <span>装备配置</span>
          </el-menu-item>
          <el-menu-item index="/skills">
            <el-icon><Magic /></el-icon>
            <span>技能配置</span>
          </el-menu-item>
          <el-menu-item index="/validation">
            <el-icon><Check /></el-icon>
            <span>配置验证</span>
          </el-menu-item>
          <el-menu-item index="/import-export">
            <el-icon><Switch /></el-icon>
            <span>导入导出</span>
          </el-menu-item>
        </el-menu>

        <!-- 统计信息卡片 -->
        <div class="stats-card" v-if="stats">
          <h3>配置统计</h3>
          <div class="stats-item">
            <span>总配置数</span>
            <span class="stats-value">{{ stats.totalConfigs }}</span>
          </div>
          <div class="stats-item">
            <span>验证评分</span>
            <span class="stats-value" :class="getScoreClass(stats.validationScore)">
              {{ stats.validationScore.toFixed(1) }}%
            </span>
          </div>
          <div class="stats-item">
            <span>健康状态</span>
            <span class="config-status" :class="stats.healthStatus">
              {{ getHealthText(stats.healthStatus) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="config-editor-content">
        <!-- 搜索和过滤工具栏 -->
        <div class="config-toolbar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索配置..."
            :prefix-icon="Search"
            style="width: 300px"
            clearable
            @input="handleSearch"
          />
          <el-select
            v-model="filterType"
            placeholder="配置类型"
            style="width: 150px"
            clearable
            @change="handleFilter"
          >
            <el-option label="装备配置" value="equipment" />
            <el-option label="技能配置" value="skill" />
            <el-option label="怪物配置" value="enemy" />
            <el-option label="道具配置" value="prop" />
            <el-option label="任务配置" value="quest" />
          </el-select>
          <el-select
            v-model="filterStatus"
            placeholder="状态"
            style="width: 120px"
            clearable
            @change="handleFilter"
          >
            <el-option label="正常" value="healthy" />
            <el-option label="警告" value="warning" />
            <el-option label="错误" value="error" />
          </el-select>
          <el-button @click="clearFilters">
            <el-icon><Delete /></el-icon>
            清除过滤
          </el-button>
        </div>

        <!-- 配置列表 -->
        <div class="config-list" v-loading="loading">
          <el-row :gutter="20">
            <el-col
              :xs="24" :sm="12" :md="8" :lg="6"
              v-for="config in filteredConfigs"
              :key="config.type"
            >
              <div class="config-item-card" @click="openConfigEditor(config)">
                <div class="config-header">
                  <div class="config-icon">
                    <el-icon size="24"><component :is="getConfigIcon(config.type)" /></el-icon>
                  </div>
                  <div class="config-status-badge" :class="config.status">
                    <el-icon size="12"><component :is="getStatusIcon(config.status)" /></el-icon>
                  </div>
                </div>
                
                <h3 class="config-title">{{ config.name }}</h3>
                <p class="config-description">{{ config.description }}</p>
                
                <div class="config-meta">
                  <div class="meta-item">
                    <span class="meta-label">配置项数量</span>
                    <span class="meta-value">{{ config.count }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">文件大小</span>
                    <span class="meta-value">{{ config.size }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">最后修改</span>
                    <span class="meta-value">{{ formatTime(config.lastModified) }}</span>
                  </div>
                </div>
                
                <div class="config-actions">
                  <el-button size="small" type="primary" @click.stop="openConfigEditor(config)">
                    编辑
                  </el-button>
                  <el-button size="small" @click.stop="validateConfig(config)">
                    验证
                  </el-button>
                  <el-dropdown @command="handleConfigAction" trigger="click" @click.stop>
                    <el-button size="small">
                      更多 <el-icon><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{action: 'export', config}">导出</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'backup', config}">备份</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'reset', config}" divided>重置</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 空状态 -->
          <el-empty
            v-if="!loading && filteredConfigs.length === 0"
            description="暂无配置数据"
            :image-size="120"
          >
            <el-button type="primary" @click="reloadConfigs">重新加载</el-button>
          </el-empty>
        </div>
      </div>
    </div>

    <!-- 导入对话框 -->
    <el-dialog v-model="showImportDialog" title="导入配置" width="600px">
      <ImportExportDialog
        mode="import"
        @success="handleImportSuccess"
        @close="showImportDialog = false"
      />
    </el-dialog>

    <!-- 导出对话框 -->
    <el-dialog v-model="showExportDialog" title="导出配置" width="600px">
      <ImportExportDialog
        mode="export"
        @success="handleExportSuccess"
        @close="showExportDialog = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'
import { useConfigStore } from '@/stores/config'
import type { ConfigListItem } from '@/types/config'
import ImportExportDialog from '@/components/ImportExportDialog.vue'

// 图标导入
import {
  Connection, Sunny, Moon, Upload, Download, Refresh, Grid, Box, Magic, Check, Switch,
  Search, Delete, ArrowDown, CircleCheck, Warning, CircleClose
} from '@element-plus/icons-vue'

const router = useRouter()
const configStore = useConfigStore()

// 主题切换
const toggleTheme = inject('toggleTheme') as () => void
const isDark = inject('isDark') as Ref<boolean>

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const filterType = ref('')
const filterStatus = ref('')
const showImportDialog = ref(false)
const showExportDialog = ref(false)

// 计算属性
const filteredConfigs = computed(() => {
  let configs = configStore.configList
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    configs = configs.filter(config => 
      config.name.toLowerCase().includes(keyword) ||
      config.description.toLowerCase().includes(keyword) ||
      config.type.toLowerCase().includes(keyword)
    )
  }
  
  // 类型过滤
  if (filterType.value) {
    configs = configs.filter(config => config.type === filterType.value)
  }
  
  // 状态过滤
  if (filterStatus.value) {
    configs = configs.filter(config => config.status === filterStatus.value)
  }
  
  return configs
})

const serverStatus = computed(() => 
  configStore.serverConnected ? 'success' : 'error'
)

const serverStatusText = computed(() => 
  configStore.serverConnected ? '已连接' : '未连接'
)

const stats = computed(() => configStore.stats)

// 方法
const handleSearch = () => {
  // 防抖处理可以在这里添加
}

const handleFilter = () => {
  // 过滤逻辑
}

const clearFilters = () => {
  searchKeyword.value = ''
  filterType.value = ''
  filterStatus.value = ''
}

const openConfigEditor = (config: ConfigListItem) => {
  // 统一使用通用配置编辑器
  router.push(`/config/${config.type}`)
}

const validateConfig = async (config: ConfigListItem) => {
  loading.value = true
  try {
    await configStore.validateConfigs(config.type)
    ElMessage.success('验证完成')
  } catch (error) {
    ElMessage.error('验证失败')
  } finally {
    loading.value = false
  }
}

const reloadConfigs = async () => {
  loading.value = true
  try {
    await configStore.loadConfigList()
    await configStore.loadStats()
    ElMessage.success('配置重新加载成功')
  } catch (error) {
    ElMessage.error('配置重新加载失败')
  } finally {
    loading.value = false
  }
}

const handleConfigAction = ({ action, config }: { action: string, config: ConfigListItem }) => {
  switch (action) {
    case 'export':
      // 导出单个配置
      break
    case 'backup':
      // 备份配置
      break
    case 'reset':
      // 重置配置
      ElMessageBox.confirm(
        `确定要重置 ${config.name} 配置吗？此操作不可撤销。`,
        '确认重置',
        {
          confirmButtonText: '重置',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 执行重置
        ElMessage.success('配置已重置')
      })
      break
  }
}

const handleImportSuccess = () => {
  showImportDialog.value = false
  reloadConfigs()
}

const handleExportSuccess = () => {
  showExportDialog.value = false
}

// 工具函数
const getConfigIcon = (type: string) => {
  const iconMap: Record<string, any> = {
    equipment: Box,
    skill: Magic,
    enemy: 'Avatar',
    prop: 'Goods',
    quest: 'Document'
  }
  return iconMap[type] || Grid
}

const getStatusIcon = (status: string) => {
  const iconMap: Record<string, any> = {
    healthy: CircleCheck,
    warning: Warning,
    error: CircleClose
  }
  return iconMap[status] || CircleCheck
}

const getScoreClass = (score: number) => {
  if (score >= 90) return 'success'
  if (score >= 70) return 'warning'
  return 'error'
}

const getHealthText = (status: string) => {
  const textMap: Record<string, string> = {
    healthy: '健康',
    warning: '警告',
    error: '错误'
  }
  return textMap[status] || '未知'
}

const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleDateString()
}

// 生命周期
onMounted(() => {
  reloadConfigs()
})
</script>

<style scoped>
.config-list {
  margin-top: 20px;
}

.config-item-card {
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 280px;
  display: flex;
  flex-direction: column;
}

.config-item-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.config-icon {
  color: var(--config-editor-primary);
}

.config-status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.config-status-badge.healthy {
  background: var(--config-editor-success);
  color: white;
}

.config-status-badge.warning {
  background: var(--config-editor-warning);
  color: white;
}

.config-status-badge.error {
  background: var(--config-editor-danger);
  color: white;
}

.config-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--config-editor-text);
}

.config-description {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: var(--config-editor-text-secondary);
  line-height: 1.5;
  flex: 1;
}

.config-meta {
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
}

.meta-label {
  color: var(--config-editor-text-secondary);
}

.meta-value {
  color: var(--config-editor-text);
  font-weight: 500;
}

.config-actions {
  display: flex;
  gap: 8px;
  margin-top: auto;
}

.stats-card {
  margin: 20px 16px;
  padding: 16px;
  background: var(--config-editor-card-bg);
  border: 1px solid var(--config-editor-border);
  border-radius: 8px;
}

.stats-card h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--config-editor-text);
}

.stats-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
}

.stats-value {
  font-weight: 600;
}

.stats-value.success {
  color: var(--config-editor-success);
}

.stats-value.warning {
  color: var(--config-editor-warning);
}

.stats-value.error {
  color: var(--config-editor-danger);
}

.config-nav-menu {
  border-right: none;
  background: transparent;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h1 {
  margin: 0;
  font-size: 20px;
  color: var(--config-editor-text);
}

.header-right {
  display: flex;
  align-items: center;
}
</style>
